from elasticsearch import Elasticsearch

INDEX_NAME = "component_library_module_search" 
ES_HOST =  "http://localhost:9200" 

def search_documents(es_client, index_name, keyword, page_number=1, page_size=10):

    from_ = (page_number - 1) * page_size # 计算分页查询的起始位置
    query = {
        "query": {
            "match": {
                "key": keyword
            }
        },
        "from": from_,
        "size": page_size
    }

    response = es_client.search(index=index_name, body=query)# 执行查询
    doc_hits = response['hits']['hits'] # 查询命中的文档列表
    total_hits = response['hits']['total']['value'] # 总命中数

    return doc_hits, total_hits

if __name__ == "__main__":
    es_client = Elasticsearch(ES_HOST) # 创建Elasticsearch客户端实例
    keywords = "张三" 
    page_size = 1 # 设置每页的大小
    # page = int(input("请输入页数："))
    page = 1  # 指定想要获得的页数

    results, total_result = search_documents(es_client=es_client, index_name=INDEX_NAME, keyword=keywords, page_number=page, page_size=page_size)
    print(f'Total hits: {total_result}\nPage Size: {page_size}')
    for result in results:
        print(result['_id'], result['_source']['key'])